<template>
  <div class="">
    <el-card>
      <!-- 步骤条 -->
      <el-steps :active="activeName-0" align-center="">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 整体表单 -->
      <el-form :model="addForm" :rules="addGoodsrules" ref="addGoodsruleForm" label-width="100px" class="demo-ruleForm">
        <!-- tab栏 -->
        <el-tabs :before-leave="beforeTabLeave" @tab-click="tabClicked" v-model="activeName" tab-position="left"
          class="mt15">

          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat" class="t-left">
              <!-- 选择商品分类的级联选择框 -->
              <el-cascader v-model="addForm.goods_cat" :options="cateList" clearable :props="cateProps"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>


          <el-tab-pane name="1" label="商品参数">

            <!-- 渲染表单item项 -->
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTableData" label-width="100%">
              <!-- 使用数组渲染复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="val" v-for="(val,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>


          <el-tab-pane name="2" label="商品属性">
            <!-- 循环生成静态属性 -->
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id" label-width="200px">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!-- 上传图片 -->
            <el-upload class="upload-demo" :headers=headerObj :action=uploadUrl :on-preview="handlePreview"
              :on-success="handleSuccess" :on-remove="handleRemove" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>

          </el-tab-pane>
          <el-tab-pane name="5" label="完成">
            <el-button type="primary" @click="btnAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <img :src=previewPath alt="" width="100%">
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    components: {},
    data() {
      return {
        //   步骤挑索引
        activeName: '0',
        // 整体表单基本信息
        addForm: {
          goods_name: '1',
          goods_cat: [1, 4, 23],
          goods_price: '1',
          goods_number: '1',
          goods_weight: '1',
          goods_introduce: '',
          pics: [],
          attrs: [],
        },
        // 级联菜单数据源
        cateList: [],
        // 级联菜单配置项
        cateProps: {
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        // 整体表单验证
        addGoodsrules: {
          goods_name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
        },
        // 参数数据
        manyTableData: [],
        // 属性数据
        onlyTableData: [],

        // 上传图片路径
        uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
        //图片上传组件的headers请求头对象
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        //保存预览图片的url地址
        previewPath: '',
        //控制预览图片对话框的显示和隐藏
        previewVisible: false,
        // 图片预览框
        dialogVisible: false,

      }
    },
    created() {
      this.getCateList()
    },
    mounted() {},
    watch: {

    },
    computed: {
      cateId() {
        return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
      }
    },
    methods: {
      getCateList() {
        this.$axios.get('categories').then(val => {
          this.cateList = val.data
        })
      },
      //   级联菜单点选时
      handleChange() {
        console.log(this.addForm.goods_cat);
      },
      //   离开tab栏之前做验证
      beforeTabLeave(activeName, oldActiveName) {
        if (oldActiveName == '0') {
          if (this.addForm.goods_cat.length < 2) {
            this.$message.error('请先选择商品分类！')
            return false
          }
          if (this.addForm.goods_name.trim() == '') {
            this.$message.error('请先填写商品名称！')
            return false
          }
          if (this.addForm.goods_price.trim() == '') {
            this.$message.error('请先填写商品价格！')
            return false
          }
          if (this.addForm.goods_number.trim() == '') {
            this.$message.error('请先填写商品数量！')
            return false
          }
          if (this.addForm.goods_weight.trim() == '') {
            this.$message.error('请先填写商品重量！')
            return false
          }
        }
      },
      //   点击tab触发
      tabClicked() {
        if (this.activeName == '1') {
          this.$axios.get('categories/' + this.cateId + '/attributes', {
            params: {
              sel: 'many'
            }
          }).then(val => {
            console.log(val);
            val.data.forEach(item => {
              item.attr_vals = item.attr_vals.trim().split(',')
            })
            this.manyTableData = val.data
          })
        } else if (this.activeName == '2') {
          this.$axios.get('categories/' + this.cateId + '/attributes', {
            params: {
              sel: 'only'
            }
          }).then(val => {
            console.log(val);

            this.onlyTableData = val.data
          })
        }
      },
      handleSuccess(flie) {
        this.addForm.pics.push({
          pic: flie.data.tmp_path
        })
      },
      handleRemove(flie) {
        //当用户点击X号删除时执行
        //形参file就是用户点击删除的文件
        //获取用户点击删除的那个图片的临时路径
        const filePath = file.data.tmp_path
        //使用findIndex来查找符合条件的索引
        const index = this.addForm.pics.findIndex(item => item.pic === filePath)
        //移除索引对应的图片
        this.addForm.pics.splice(index, 1)
      },
      //   预览图片
      handlePreview(flie) {
        this.dialogVisible = true
        this.previewPath = flie.response.data.url
      },
      // 提交添加
      btnAdd() {
        this.addForm.goods_cat = this.addForm.goods_cat.join(",");
        //处理动态参数
        this.manyTableData.forEach(item => {
          let temp = {
            attr_id: item.attr_id,
            //转换为字符串
            attr_vals: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(temp);
        })
        //处理静态参数
        this.onlyTableData.forEach(item => {
          let temp = {
            attr_id: item.attr_id,
            //转换为字符串
            attr_vals: item.attr_vals,
          };
          this.addForm.attrs.push(temp);
        })
        this.$axios.post("goods", this.addForm).then(val => {
          console.log(val);
          if (val.meta.status != 201) {
            return this.$message.error("请求发送失败!");
          }
          this.$router.push("/goods");
        })
      }
    }
  }

</script>
<style lang="css" scoped>
  .el-tab-pane {
    border: 1px solid #eee;
  }

</style>
